<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_app_class('admin', 'admin', 0);
pc_base::load_sys_class('form', '', 0);
pc_base::load_app_func('global');
pc_base::load_app_class('api56', 'iappVideo', 0);
class manages extends admin {

    private $db;
    function __construct() {
        parent::__construct();
        $this->db = pc_base::load_model('iappVideo_model');
		$this->db_iappVideo_category = pc_base::load_model('iappVideo_category_model');
    }

    /**
     * 视频管理
     */
    public function init() {
        $where = '';
        $page = $_GET['page'];
        $pagesize = 20;
        if($_GET['q']){
            if (isset($_GET['type'])) {
                if ($_GET['type']==1) {
                    $where .= ' `vid`=\''.$_GET['q'].'\'';
                } else {
                    $where .= " `title` LIKE '%".$_GET['q']."%'";
                }
            }
        }
        
        if (isset($_GET['start_addtime']) && !empty($_GET['start_addtime'])) {
            $where .= !empty($where) ? ' AND `addtime`>=\''.strtotime($_GET['start_addtime']).'\'' : ' `addtime`>=\''.strtotime($_GET['start_addtime']).'\'';
        }
        if (!empty($_GET['end_addtime'])) {
            $where .= !empty($where) ? ' AND `addtime`<=\''.strtotime($_GET['end_addtime']).'\'' : ' `addtime`<=\''.strtotime($_GET['end_addtime']).'\'';
        }
        $infos = $this->db->listinfo($where, 'id DESC', $page, $pagesize);
        $pages = $this->db->pages;
        include $this->admin_tpl('video_list'); 
    }

    /**
     * 视频添加方法
     */
    public function add() {
        //读取配置文件
        $m_db = pc_base::load_model('module_model');
        $data = array();
        //更新模型数据库,重设setting 数据. 
        $data = $m_db->select(array('module'=>'iappVideo'));
        $setting = string2array($data[0]['setting']);
        $params = array(
            'fields'   =>$setting['fields'],
            'sid'      =>$_SESSION['userid'],
            'css'      =>$setting['css'],
            'rurl'     =>$setting['rurl'],
            'ourl'     =>$setting['ourl'],
            'pc_hash' =>$_SESSION['pc_hash'],
        ); 
		
		$iappVideo_category = $this->db_iappVideo_category->select('','*','','`listorder` DESC');
		
		if (isset($_POST['dosubmit'])) {
		    $_data = $_POST['data'];
			
			if (!$_data['title']){
				showmessage('请填写视频名称',HTTP_REFERER);
			}
			
			if (!$_data['video_url']){
				showmessage('请上传视频',HTTP_REFERER);
			}
			if (!$_data['thumb']){
				showmessage('请上传视频图片',HTTP_REFERER);
			}
			
			
			
			
			$info[userid] = $_SESSION['userid'];
			$info[username] = param::get_cookie('admin_username');

			$info['vid'] = 0;
			$info['title'] = trim($_data['title']);
			$info['content'] = trim($_data['content']);
			$info['tags'] = trim($_data['tags']);
			$info['thumb'] = $_data['thumb'];
			$info['player'] = '';
			$info['url_56'] = '';
			$info['video_url'] = $_data[video_url];
			$info['totaltime'] = $_data[totaltime];
			
			
			$info['forbid'] = 'n';
			$info['chk'] = 'y';
			$info['vtypes'] = 2;
			$info['addtime'] = time();
			$info['edittime'] = time();
			
			$id = $this->db->insert($info,true);
			$this->db->update(array('url'=>APP_PATH.'index.php?m=iappVideo&c=index&a=show&id='.$id),array('id'=>$id));
			
			showmessage('保存成功', 'index.php?m=iappVideo&c=manages&a=init');
		}else{
			include $this->admin_tpl('video_add');
		}
    }

    /**
     * function edit
     * 视频编辑控制器
     */
    public function edit() {
        $id = intval($_GET['id']);
        if (!$id){
			showmessage('参数错误');
		}
        if (isset($_POST['dosubmit'])) {
            $info = $this->db->get_one(array('id'=>$id));
            $data = $_POST['data'];
			$data[url] = APP_PATH.'index.php?m=iappVideo&c=index&a=show&id='.$info[id];
            
            if (!$data['title']){
				showmessage('请填写视频名称',HTTP_REFERER);
			}
			if (!$data['thumb']){
				showmessage('请上传视频图片',HTTP_REFERER);
			}
			if($info['vid']==0){
				if (!$data['video_url']){
					showmessage('请上传视频视频',HTTP_REFERER);
				}
			}
			
			$this->db->update($data,array('id'=>$id));
			if($info['vtypes']==1){
				$rs = Open::Video_Update(array('vid'=>$info[vid],'title'=>$data['title'],'desc'=>$data['content'],'desc'=>$data['content'],'tag'=>$data['tags']));
				if ($rs["errno"]){
				   showmessage($rs["err"],HTTP_REFERER);//远程更新失败
				}else{
					showmessage('远程更新失败' ,HTTP_REFERER);
				}
			}else{
                showmessage('更新成功', 'index.php?m=iappVideo&c=manages&a=init');
			}
        } else {
			$iappVideo_category = $this->db_iappVideo_category->select('','*','','`listorder` DESC');
            $info = $this->db->get_one(array('id'=>$id));
            include $this->admin_tpl('video_edit');
        }
    }

    /**
     * function delete
     * 删除视频控制器
     */
    public function delete() {
        $id = intval($_GET['id']);
        if (!$id) showmessage('参数错误');
        $info = $this->db->get_one(array('id'=>$id), 'vid,vtypes');
        if (!$info) showmessage('要删除的视频不存在');
        if ($info['vtypes']==1) {
           $rs = Open::Video_Delete(array('vid'=>$info['vid']));
        }
        if ($this->db->delete(array('id'=>$id))) {
            showmessage('视频删除成功', HTTP_REFERER);
        }else{
            showmessage('视频删除失败', HTTP_REFERER);
        }

    }

    // 56视频导入
    public function import_56video(){
        pc_base::load_sys_class('format','',0);
        $c56      = isset($_GET['c56']) ? $_GET['c56'] : 0;
        $type     = isset($_GET['type']) ? $_GET['type'] : 'hot';
        $t        = isset($_GET['t']) ? $_GET['t'] : '';
        $keyword  = isset($_GET['keyword']) ? $_GET['keyword'] : '';
        $page     = isset($_GET['page']) ? $_GET['page'] : '1';
        $pagesize = 20;
        if ($keyword) { //搜索时

            //由于56接口参数不统一，所有这样转换下
            switch ($type) {
                case 'hot':
                    $s = 2;
                    break;
                case 'ding':
                    $s = 3;
                    break;
                case 'new':
                    $s = 1;
                    break;
                case 'share':
                    $s = 3;
                    break;
                case 'comment':
                    $s = 6;
                    break;
                default:
                    $s = 1;
                    break;
            }
            $params = array(
                'keyword' =>$keyword,
                // 'c'    =>$c56, 官方说给这个参数会有BUG
                'page'    =>$page,
                'rows'    =>$pagesize,
                't'       =>$t,
                's'       =>$s //1，最新上传（默认）2，浏览次数 3，相关程序 4，最多收藏 5，最高评分 6，时长 7，最多打分
                );
            $data = Open::Video_Search($params);
			
            $totals = $data["total"];
            unset($data["total"]);
            foreach ($data as $key => $value) {
                $list[$key]['Content'] = $value['content'];
                $list[$key]['Subject'] = $value['title'];
                $list[$key]['tag']     = $value['tag'];
                $list[$key]['id']      = $value['id'];
                $list[$key]['user_id'] = $value['user_id'];
                $list[$key]['img']     = $value['img'];
            }
        }else{
            $params = array(
                'type' =>$type,
                'c'    =>$c56,
                't'    =>$t,
                'page' =>$page,
                'rows' =>$pagesize
            );
            $data   = Open::Video_All($params);
			//print_r($data);
            $totals = $data["total"];
            $list   = $data["data"];
        }
        include $this->admin_tpl('import_56video'); 
    }
    // 预览导入56视频列表中的视频
    public function preview_56video(){
        $vid = $_GET['vid'];
        $app = include dirname(__FILE__).'/classes/sdk56/conf.php';
        include $this->admin_tpl('priview_56video');
    }

    // 导入56视频入库
    public function doimport(){
        $ids = $_POST['ids'];
        if (!is_array($ids)) {
			showmessage('您没有勾选信息', HTTP_REFERER);
		}
		
		$c = 0;
        foreach ($ids as $i) {
		
			$_data = Open::Video_GetVideoInfo(array('vid'=>$i));
			
			if($_data[code]==0){
				$_data = $_data[0];
				
				$data[userid] = $_SESSION['userid'];;
				$data[username] = param::get_cookie('admin_username');
				
				$data['vid'] = $_data['vid'];
				$data['title'] = trim($_data['title']);
				$data['content'] = trim($_data['desc']);
				$data['tags'] = trim($_data['tags']);
				$data['thumb'] = $_data['bimg'];
				$data['player'] = $_data[swf];
				$data['url_56'] = $_data[url];
				$data['video_url'] = '';
				$data['totaltime'] = $_data[totaltime];
				
				$data['forbid'] = 'n';
				$data['chk'] = 'y';
				$data['vtypes'] = 0;
				$data['addtime'] = time();
				$data['edittime'] = time();
				
				$id = $this->db->insert($data,true);
				//echo $id;
				$id = $this->db->update(array('url'=>APP_PATH.'index.php?m=iappVideo&c=index&a=show&id='.$id),array('id'=>$id));
				//echo $id;
				$c++;
			}
        }
        showmessage('成功导入'.$c.'个视频', HTTP_REFERER);
    }

	
    // 模块配置
    public function setting(){
        $m_db = pc_base::load_model('module_model');
        if(isset($_POST['dosubmit'])) {
            if(is_array($_POST['fields'])){
              $_POST['setting']['fields'] = implode(',',$_POST['fields']);
            }else{
                $_POST['setting']['fields'] = 'title,content,tags';
            }

            //保存接口配置
            $app = $_POST["app"];
            if (is_array($app)) {
                arr2file(dirname(__FILE__).'/classes/sdk56/conf.php', $app);
            }

            //更新模型数据库,重设setting 数据. 
            $setting = array2string($_POST['setting']);
            $m_db->update(array('setting'=>$setting),array('module'=>'iappVideo'));
            showmessage('设置成功',HTTP_REFERER);
        } else {
            //读取配置文件
            $data = array();
            //更新模型数据库,重设setting 数据. 
            $data = $m_db->select(array('module'=>'iappVideo'));
            $setting = string2array($data[0]['setting']);
            $fields = explode(',', $setting['fields']);

            //读取接口配置
            $app = include dirname(__FILE__).'/classes/sdk56/conf.php';

            include $this->admin_tpl('video_setting');
        }
    }

    // 视频预览
    public function public_view_video(){
        $id = intval($_GET['id']);
        if (!$id) showmessage('请选择要浏览的视频！');
        $info = $this->db->get_one(array('id'=>$id));
        include $this->admin_tpl('view_video');
    }
	
	
	function category_list() {
		$page = max(intval($_GET['page']), 1);
		$data = $this->db_iappVideo_category->listinfo('', '`listorder` DESC', $page);
		include $this->admin_tpl('category_list');
	}
	
	function category_add() {
		if($_POST['dosubmit']) {
			$info = $_POST['info'];
			$info[title] = trim($_POST['info'][title]) ? trim($_POST['info'][title]) : showmessage(L('主题不能为空'),HTTP_REFERER);
			$info[listorder] = 0;
			$return_id = $this->db_iappVideo_category->insert($info,'1');
			showmessage(L('add_success'), '?m=iappVideo&c=manages&a=category_list&menuid='.$_GET['menuid']);
		} else {
			include $this->admin_tpl('category_add');
		}		
	}
	
	function category_edit() {
		if($_POST['dosubmit']) {
			$id = intval($_POST['id']) ? intval($_POST['id']) : showmessage(L('parameter_error'),HTTP_REFERER);
			$info = $_POST['info'];
			$info[title] = trim($_POST['info'][title]) ? trim($_POST['info'][title]) : showmessage(L('主题不能为空'),HTTP_REFERER);
			$return_id = $this->db_iappVideo_category->update($info,array('id'=>$id));
			showmessage(L('operation_success'), '?m=iappVideo&c=manages&a=category_edit&id='.$id.'&menuid='.$_GET['menuid']);
		} else {
			$id = intval($_GET['id']) ? intval($_GET['id']) : showmessage(L('parameter_error'),HTTP_REFERER);		
			$info = $this->db_iappVideo_category->get_one(array('id'=>$id));
			include $this->admin_tpl('category_edit');			
		}
	}
	
	/**
	 * 删除
	 */
	public function category_delete() {
		$siteid = $this->siteid;
		
		if (isset($_GET['id']) && !empty($_GET['id'])) {
			$id = intval($_GET['id']);
			$this->db_iappVideo_category->delete(array('id'=>$id));
			showmessage(L('operation_success'), HTTP_REFERER);
		} elseif (isset($_POST['ids']) && !empty($_POST['ids'])) {
			if (is_array($_POST['ids'])) {
				foreach ($_POST['ids'] as $fid) {
					$this->db_iappVideo_category->delete(array('id'=>$fid));
				}
			}
			showmessage(L('operation_success'), HTTP_REFERER);
		} else {
			showmessage(L('illegal_operation'), HTTP_REFERER);
		}
	}
	
	/**
	 * 排序
	 */
	public function category_listorder() {
		if (isset($_POST['listorders']) && is_array($_POST['listorders'])) {
			$listorder = $_POST['listorders'];
			foreach ($listorder as $k => $v) {
				$this->db_iappVideo_category->update(array('listorder'=>$v), array('id'=>$k));
			}
		}
		showmessage(L('operation_success'), HTTP_REFERER);
	}
}
?>